package com.mq.delay;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author ytj
 * @date 2024/1/16
 */
@Component
public class Demo8Producer {
    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * @param delay  延迟时间（单位毫秒）
     * */
    public void send(Integer id,Integer delay){
        Demo8Message demo8Message=new Demo8Message(id);
        this.rabbitTemplate.convertAndSend(Demo8Message.EXCHANGE, Demo8Message.ROUTINGKEY, demo8Message, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                if(delay!=null&&delay>0){
                    message.getMessageProperties().setExpiration(String.valueOf(delay));
                }
                return message;
            }
        });
    }
}
